package com.b511.swpu.cementbackend.service.impl;

import com.b511.swpu.cementbackend.entity.MetaSystemUnit;
import com.b511.swpu.cementbackend.entity.SysUser;
import com.b511.swpu.cementbackend.exception.CementException;
import com.b511.swpu.cementbackend.repository.MetaSystemUnitRepository;
import com.b511.swpu.cementbackend.repository.SysUserRepository;
import com.b511.swpu.cementbackend.service.MetaCategoryService;
import com.b511.swpu.cementbackend.util.UserUtil;
import com.b511.swpu.cementbackend.util.enumeration.Code;
import com.b511.swpu.cementbackend.util.Help;
import com.b511.swpu.cementbackend.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Service
public class MetaCategoryServiceImpl implements MetaCategoryService {

    private final UserUtil userUtil;

    private final MetaSystemUnitRepository metaSystemUnitRepository;

    private final SysUserRepository sysUserRepository;

    public MetaCategoryServiceImpl(MetaSystemUnitRepository metaSystemUnitRepository, SysUserRepository sysUserRepository, UserUtil userUtil) {
        this.metaSystemUnitRepository = metaSystemUnitRepository;
        this.sysUserRepository = sysUserRepository;
        this.userUtil = userUtil;
    }

    @Override
    @Transactional
    public R updateUserUnit(Long metaSystemUnitId) {
        Optional<MetaSystemUnit> metaSystemUnit = metaSystemUnitRepository.findById(metaSystemUnitId);
        if (!metaSystemUnit.isPresent()) {
            throw new CementException(Code.SELECT_FAIL);
        }
        SysUser user = userUtil.getCurrentUser().setMetaSystemUnit(metaSystemUnit.get());
        sysUserRepository.save(user);
        return R.ok();
    }
}
